from django.shortcuts import render, redirect
from app import models
from django import forms
from django.core.validators import RegexValidator, ValidationError
from app.utils.pagination import Pagination

# Create your views here.

"""部门管理"""


def depart_list(request):
    """ 部门列表"""
    qu = models.Department.objects.all()
    return render(request, 'depart_list.html', {'qu': qu})


def depart_add(request):
    """新增部门"""
    if request.method == 'GET':
        return render(request, 'depart_add.html')
    title = request.POST.get('title')
    models.Department.objects.create(title=title)
    return redirect('/depart/list')


def depart_delete(request):
    """删除部门"""
    nid = request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect('/depart/list')


def depart_update(request, nid):
    if request.method == 'GET':
        query = models.Department.objects.filter(id=nid)
        return render(request, 'depart_update.html', {'query': query})
    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list')


"""用户管理"""


def user_list(request):
    query = models.UserInfo.objects.all()
    return render(request, 'user_list.html', {'query': query})


class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=3, label="用户名")

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "accout", "create_time", "gender", "depart"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_add(request):
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_add.html', {"form": form})
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # print(form.cleaned_data)
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_add.html', {"form": form})


def user_update(request, nid):
    obj = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        form = UserModelForm(instance=obj)
        return render(request, 'user_update.html', {'form': form})
    form = UserModelForm(data=request.POST, instance=obj)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要在用户以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list')


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')


# class PhoneModelForm(forms.ModelForm):


def phone_list(request):
    """
    靓号管理
    基础查询方式
    """
    # query = models.Phone.objects.all().order_by("-level")
    # return render(request, 'phone_list.html', {"query": query})
    # for i in range(300):
    #     models.Phone.objects.create(models="18188888818", price=10, level=1, status=1)


    """
    通过创建类和方法实现（查询、分页）
    """
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data
    # 分页
    queryset = models.Phone.objects.filter(**data_dict).order_by("-level")
    page_object = Pagination(request, queryset)
    context = {"search_data": search_data,
               "queryset": page_object.page_queryset,
               "page_string": page_object.html()
               }
    return render(request, 'phone_list.html', context)


class PhoneModelForm(forms.ModelForm):
    # 校验方式1
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[ RegexValidator(r'^1[3-9]\d{9}$', '必须为数字')]
    # )
    class Meta:
        model = models.Phone
        # fields = "__all__"
        fields = ["mobile", "price", "level", "status"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证方式二
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.Phone.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过
        return txt_mobile


def phone_add(request):
    if request.method == "GET":
        form = PhoneModelForm()
        return render(request, 'phone_add.html', {"form": form})
    form = PhoneModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/phone/list/")
    return render(request, 'phone_add.html', {"form": form})


def phone_delete(request, nid):
    models.Phone.objects.filter(id=nid).delete()
    return redirect('/phone/list')


class PhoneUpdateModelForm(forms.ModelForm):
    # mobile = forms.CharField(disabled=True, label="手机号")
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '必须为数字')]
    )

    class Meta:
        model = models.Phone
        # fields = ["price", "level", "status"]
        fields = ["mobile", "price", "level", "status"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    def clean_mobile(self):
        # 当前编辑的那一行的ID
        # self.instance.pk
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.Phone.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")
        # 验证通过
        return txt_mobile


def phone_update(request, nid):
    obj = models.Phone.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PhoneUpdateModelForm(instance=obj)
        return render(request, 'phone_update.html', {'form': form})
    form = PhoneUpdateModelForm(data=request.POST, instance=obj)
    if form.is_valid():
        form.save()
        return redirect("/phone/list")
    return render(request, 'phone_update.html', {'form': form})